<script setup>
import { ref,nextTick, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { getToken } from "@/utils/auth";

const props = defineProps({
    //上传地址
    action:{
        default:"/gateway/jy-system/file/uploadOssFile",
        type:String
    },
    //上传携带的额外参数
    otherParams:{
        default:{},
        type:Object
    },
    //上传请求头
    requestHeaders:{
        default:{
            Authorization: `Bearer ${getToken()}`,
        },
        type:Object
    },
    //上传大小限制
    limitSize:{
        default:20 * 1024 * 1024,
        type:Number
    },
    //是否多传
    multiple:{
        default:false,
        type:Boolean
    },
    //多传下，最大上传数量
    maxFileLength:{
        default:5,
        type:Number
    },
    fileUrlInfo:{
        default:() => ({}),
        type:Object
    },
    fileListUrlInfo:{
        default:[],
        type:Array
    },
     //文件类型限制
     FileType:{
        default:['application/pdf'],
        type:Array
    },
})
const baseUrl = import.meta.env.VITE_APP_UPLOADURL;
const emit = defineEmits(["backValue"])
const fileUrlData = ref(props.fileUrlInfo)
const fileList = ref(props.fileListUrlInfo);

//上传的文件数量
const uploadFileLength = ref(props.fileListUrlInfo.length);


watch(props,()=>{
    // console.log(props.fileUrlInfo,'props.fileUrlInfo');
    fileUrlData.value = props.fileUrlInfo;
    fileList.value = props.fileListUrlInfo || [];
    uploadFileLength.value = fileList.value.length;

},{
    deep:true,
    immediate:true
})

//上传成功回调
const handleFileSuccess = (response,uploadFile) => {

    if(response.code == 0){
        if(props.multiple){
            fileList.value.push(response.data.fileUrl);
            uploadFileLength.value = fileList.value.length;
        }else{
            fileUrlData.value = response.data;
        }
        emitBackValue();
    }else{
        ElMessage.error('上传失败') 
    }
}
const handleFileError = (response)=>{
    ElMessage.error('上传失败') 
}
//上传前条件判断
const beforeFileUpload= (file) => {

    if(props.multiple){
        let fileLength = Number(uploadFileLength.value);
        fileLength++;

        if(fileLength>props.maxFileLength){
            return false;
        }
        
    }
    if(!(props.FileType.indexOf(file.type) != -1)){
        ElMessage({
            message: '请上传正确的文件格式',
            type: 'warning'
        });
        return false;
    }

    if(file.size > props.limitSize){
        ElMessage({
            message: '文件上传过大',
            type: 'warning'
        });
        return false;
    }
    return true
}
//移除文件
const removeFile = (index)=>{
    if(props.multiple){
        fileList.value.splice(index,1);
        uploadFileLength.value -- ;
    }else{
        fileUrlData.value = {};
    }
    emitBackValue();
}
const emitBackValue = ()=>{
    if(props.multiple){
        emit("backValue",fileList.value)
    }else{
        emit("backValue",fileUrlData.value)
    }
}
</script>
<template>
    <div class="upload-file">
        <div class="upload-btn">
            <el-upload
                :action="baseUrl + action"
                :data="otherParams"
                :headers="requestHeaders"
                :show-file-list="false"
                :multiple="multiple"
                :on-success="handleFileSuccess"
                :before-upload="beforeFileUpload"
                :on-error="handleFileError"
            >
                <el-button  type="primary" >点击上传</el-button>
            </el-upload>
            <div class="tips">
                <slot name="tips"></slot>
            </div>
        </div>
        <div class="file-list" v-if="multiple">

            <div class="lis" v-for="(item,index) in fileList" :key="index" :id="item">
                <div class="left-info">
                    <img src="@/assets/images/upload-file.png" alt="">
                    <div class="text">{{ item }}</div>
                </div>
                <div class="right-info">
                    <div class="img" @click.stop="removeFile(index)"></div>
                </div>
            </div>
        </div>
        <div class="file-list" v-else>

            <div class="lis" >
                <div class="left-info">
                    <img src="@/assets/images/upload-file.png" alt="" v-if="fileUrlData?.fileUrl">
                    <div class="text">{{ fileUrlData.fileName }}</div>
                </div>
                <div class="right-info" v-if="fileUrlData?.fileUrl">
                    <div class="img" @click.stop="removeFile"></div>
                </div>
            </div>
        </div>
    </div>

</template>
<style lang="less" scoped>
.upload-file{
    width: 100%;
}
.upload-btn{
    width: 100%;
    display:flex;
    justify-content: flex-start;
    align-items: center;
    .tips{
        margin-left:8px;

    }
}
.file-list{
    width: 100%;
    .lis{
        width: 100%;

        display: flex;
        margin:0 4px;
        margin-top:8px;
        box-sizing: border-box;
        justify-content: space-between;
        background: #fff;
        
        .left-info{
            display: flex;
            justify-content: flex-start;
            align-items: center;
            height: 100%;
            width: calc(100% - 12px);
            img{
                width: 12px;
                height: 12px;
                
            }
            .text{
                margin-left:4px;
                color:#222222;
                font-size: 12px;
                line-height: 16px;
                width: calc(100% - 16px);
            }
        }
        .right-info{
            display: flex;
            justify-content: flex-start;
            align-items: center;
            height: 100%;
            width: 12px;
            cursor: pointer;
            .img{
                width: 100%;
                height: 12px;
                background: url('@/assets/images/upload-success.png');
                background-size: 100% 100%;
            }
        }
        &:hover{
            background: #F3F3F3;
            .right-info{
                .img{
                    width: 12px;
                    height: 12px;
                    background: url('@/assets/images/upload-close.png');
                    background-size: 100% 100%;
                } 
            }
        }
    }
}
</style>